package net.lesscoding.web.client;

import lombok.extern.slf4j.Slf4j;
import net.lesscoding.utils.ByteBufferUtil;
import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @author eleven
 * @date 2024/10/22 10:09
 * @apiNote
 */
@Slf4j
public class ClientTest1 {
    @Test
    public void clientSocketChannelTest() {
        // 1. 创建一个SocketChannel
        try (SocketChannel socketChannel = SocketChannel.open();) {
            // 2. 连接到服务器
            socketChannel.connect(new InetSocketAddress("localhost", 8080));
            // 3. 发送数据
            socketChannel.write(ByteBuffer.wrap("Hello, Server!\n111111\n2222\n3333333\n44445".getBytes()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Test
    public void receiveClientTest() {
        // 1. 创建一个SocketChannel
        try (SocketChannel socketChannel = SocketChannel.open();) {
            // 2. 连接到服务器
            socketChannel.connect(new InetSocketAddress("localhost", 8080));
            int count = 0;
            // 3. 接收数据
            while (true) {
                ByteBuffer byteBuffer = ByteBuffer.allocate(1024 * 8);
                int read = socketChannel.read(byteBuffer);
                ByteBufferUtil.debugAll(byteBuffer);
                if (read != -1) {
                    count += read;
                    log.info("当前总共接收了 {} 字节", count);
                }
                byteBuffer.clear();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
